package com.etc.reflectdemo;

import com.etc.reflectdemo.entity.Book;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author: knowno
 * @create: 2024-09-18 16:04
 * @Version 1.0
 **/
public class TestBeanInfo {
    public static void main(String[] args) throws IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException {

        //要使用自省相关的api接口和类做操作
        //1 得到一个BeanInfo对象
        BeanInfo beanInfo = Introspector.getBeanInfo(Book.class);

        Book book = Book.class.newInstance();

        //2。 Beaninfo对象的常见方法
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        //输出数组元素
//        System.out.println(Arrays.toString(propertyDescriptors));
        System.out.println(propertyDescriptors.length);

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            System.out.println(propertyDescriptor.getName() + " , " + propertyDescriptor.getPropertyType() + " , " + propertyDescriptor.getReadMethod() + " ," + propertyDescriptor.getWriteMethod());

            Method writeMethod = propertyDescriptor.getWriteMethod();

            //调用某个方法[seter/getter]
            Object test = writeMethod.invoke(book, "test");
        }

    }
}
